package com.syq.realm;

import com.syq.mapper.SysUsersMapper;
import com.syq.pojo.SysUsers;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @ClassName: MyRealm
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/18 16:51
 * AuthenticatingRealm 认证
 * AuthorizingRealm 授权
 */


public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUsersMapper sysUsersMapper;

    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户对象
        SysUsers sysUsers = (SysUsers) principalCollection.getPrimaryPrincipal();

        //查询角色
        Set<String> roles=sysUsersMapper.findRoles(sysUsers.getId());
        //查询权限
        Set<String> stringPermissions=sysUsersMapper.findPerms(sysUsers.getId());

        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //授权对象
        authorizationInfo.setRoles(roles);

        authorizationInfo.setStringPermissions(stringPermissions);

        return authorizationInfo;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        //用户名
        String username = token.getUsername();
        //密码
        String password = new String(token.getPassword());
        //校验用户名密码是否正确

        SysUsers user = sysUsersMapper.findUserByName(username);

        if (null==user){
            System.out.println("用户名不存在");
            throw new UnknownAccountException();
        }
        if (!user.getPassword().equals(password)){
            System.out.println("密码不正确");
            throw new IncorrectCredentialsException("密码不正确");
        }
        //正确放行  （Object）用户名,（Object）密码,当前名
        return new SimpleAuthenticationInfo(user,password,this.getName());
//        return new SimpleAuthenticationInfo(username,password,this.getName());  用户名 不推荐。可能造成类型转换异常。subject.getPrincipal()取第一个参数，当为username时没有办法将字符串转换为SysUsers
    }
}
